package com.xbongbong.parent.parse.data;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.xbongbong.paas.domain.entity.PaasFormExplainEntity;
import com.xbongbong.paas.domain.entity.ext.PaasFormDataEntityExt;
import com.xbongbong.paas.enums.FieldTypeEnum;
import com.xbongbong.paas.field.FieldAttrEntity;
import com.xbongbong.paas.field.LinkInfoPojo;
import com.xbongbong.paas.field.MultiUnitItemPoJo;
import com.xbongbong.paas.help.ProFormHelp;
import com.xbongbong.paas.pojo.dto.FormDataGetDTO;
import com.xbongbong.paas.pojo.vo.LinkResultDataDTO;
import com.xbongbong.paas.pojo.vo.LinkResultDataVO;
import com.xbongbong.paas.toolbox.exception.XbbException;
import com.xbongbong.paas.toolbox.util.BeanUtil;
import com.xbongbong.paas.util.ExplainUtil;
import com.xbongbong.pro.enums.errorcodes.SystemErrorCodeEnum;
import com.xbongbong.pro.formdata.pojo.dto.LinkDataDTO;
import com.xbongbong.saas.domain.entity.WorkOrderExplainEntity;
import com.xbongbong.saas.enums.XbbRefTypeEnum;
import com.xbongbong.saas.help.RelativeProductHelp;
import com.xbongbong.sys.domain.entity.DepartmentEntity;
import com.xbongbong.sys.domain.entity.UserEntity;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * @author: wufeng
 * @date: 2018/11/9 15:40
 * @desrcption: 表单详情处理关联数据的问题
 */
@Service("formDataLinkDataGetServiceImpl")
public class FormDataLinkDataGetServiceImpl extends BaseFormDataLinkDataHelp  {

    private static  final Logger LOG = LoggerFactory.getLogger(FormDataLinkDataGetServiceImpl.class);

    @Resource
    private RelativeProductHelp relativeProductHelp;
    @Resource
    private LinkDataHelp linkDataHelp;

    /**
     * 关联数据的数据查询
     * @param formDataGetDTO
     * @param linkResultDataVO 关联数据容器
     * @return
     * @throws XbbException
     */
    public JSONObject formDataLinkDataGet(FormDataGetDTO formDataGetDTO, LinkResultDataVO linkResultDataVO) throws XbbException {
        JSONObject resultJsonObject = new JSONObject();
        resultJsonObject.putAll(linkResultDataVO.getData());
        try {

            Map<String, FieldAttrEntity> explainMap = linkResultDataVO.getExplainMap();
            JSONObject data = linkResultDataVO.getData();

            // 工单处理
            List<LinkInfoPojo> linkInfoList = ProFormHelp.getLinkInfo(linkResultDataVO.getExplainList());
            List<Long> formIdList = new ArrayList<>();
            List<Long> workOrderFormIdList = new ArrayList<>();
            boolean hasProductLinkForm = false;
            for (LinkInfoPojo linkInfoPojo : linkInfoList) {
                if (Objects.nonNull(linkInfoPojo)) {
                    if (Objects.equals(XbbRefTypeEnum.WORK_ORDER.getCode(), linkInfoPojo.getLinkBusinessType())) {
                        workOrderFormIdList.add(linkInfoPojo.getLinkFormId());
                    } else {
                        if (!hasProductLinkForm && Objects.equals(linkInfoPojo.getLinkBusinessType(), XbbRefTypeEnum.PRODUCT.getCode())) {
                            hasProductLinkForm = true;
                        }
                        formIdList.add(linkInfoPojo.getLinkFormId());
                    }
                }
            }
            if (formIdList.isEmpty() && workOrderFormIdList.isEmpty()) {
                return resultJsonObject;
            }

            // 非工单解释
            Map<String, PaasFormExplainEntity> formExplainMap = getExplainMapByFormIdList(formIdList, formDataGetDTO.getCorpid());
            // 工单解释
            Map<String, WorkOrderExplainEntity> workOrderFormExplainMap = getWorkOrderExplainMapByFormId(workOrderFormIdList, formDataGetDTO.getCorpid());

            LinkResultDataDTO linkResultDataDTO = new LinkResultDataDTO();
            BeanUtil.copyProperties(formDataGetDTO, linkResultDataDTO);
            linkResultDataDTO.setIsPrint(formDataGetDTO.getIsPrint());
            // 获取数据
            Map<String, PaasFormDataEntityExt> formDataMap = linkDataHelp.getLinkData4Field(linkResultDataDTO, linkResultDataVO);
            // 解析关联字段的数据
            LinkDataDTO linkDataDTO = new LinkDataDTO();
            if (hasProductLinkForm) {
                Map<Long, MultiUnitItemPoJo> groupBaseUnitMap = relativeProductHelp.getGroupBaseUnitMap(linkResultDataDTO.getCorpid());
                linkDataDTO.setGroupBaseUnitMap(groupBaseUnitMap);
            }
            BeanUtil.copyProperties(linkResultDataDTO, linkDataDTO);
            linkDataDTO.setMainUserMap(linkResultDataVO.getMainUserMap());
            linkDataDTO.setCoUserMap(linkResultDataVO.getCoUserMap());
            linkDataDTO.setIsPrint(formDataGetDTO.getIsPrint());
            this.analysisLinkData(explainMap, data, resultJsonObject, formDataMap, linkResultDataVO, formExplainMap, workOrderFormExplainMap, linkDataDTO);
        } catch (Exception e) {
            LOG.error("获取关联数据失败，", e);
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, SystemErrorCodeEnum.API_ERROR_100001.getMsg());
        }
        return resultJsonObject;
    }

    /**
     * 详情返回对应格式的数据
     * @param explainMap 字段容器
     * @param data 关联的数据
     * @param resultJsonObject 返回的数据
     * @param formDataMap
     * @param linkResultDataVO
     * @param formExplainMap
     * @throws XbbException
     */
    public void analysisLinkData(Map<String, FieldAttrEntity> explainMap, JSONObject data, JSONObject resultJsonObject, Map<String, PaasFormDataEntityExt> formDataMap,
                                 LinkResultDataVO linkResultDataVO, Map<String, PaasFormExplainEntity> formExplainMap, Map<String, WorkOrderExplainEntity> workOrderFormExplainMap, LinkDataDTO linkDataDTO) throws XbbException {
        // 关联数据的表单业务类型（非被关联表单类型）
        Integer businessType = linkDataDTO.getBusinessType();
        Iterator iterator = linkResultDataVO.getLinkData().keySet().iterator();
        Map<String, UserEntity> userMap = linkResultDataVO.getUserMap();
        Map<String, DepartmentEntity> departmentMap = linkResultDataVO.getDepartmentMap();
        while (iterator.hasNext()){
            String key = iterator.next().toString();
            FieldAttrEntity fieldAttrEntity = explainMap.get(key);
            if(fieldAttrEntity == null){
                resultJsonObject.put(key, data.get(key));
                continue;
            }
            if(ExplainUtil.isSubForm(fieldAttrEntity.getFieldType()) && Objects.equals(1, linkDataDTO.getIsPrint())){
                JSONArray resultList = getSubFormLinkData(fieldAttrEntity, linkDataDTO, data, linkResultDataVO, formExplainMap, workOrderFormExplainMap, formDataMap);
                resultJsonObject.put(key, resultList);
            } else if (Objects.equals(FieldTypeEnum.LINK_DATA.getType(), fieldAttrEntity.getFieldType()) || Objects.equals(FieldTypeEnum.LINK_DATA_MULTI.getType(), fieldAttrEntity.getFieldType())){
                // 详情无需解析子表单的关联数据
                setLinkData(fieldAttrEntity, data, resultJsonObject, userMap, departmentMap, linkDataDTO, formExplainMap, workOrderFormExplainMap, businessType, formDataMap, fieldAttrEntity.getLinkInfo().getLinkedAttr());
            } else {
                resultJsonObject.put(key, data.get(key));
            }
        }

    }

}
